<template>
  <d2-container>
    <vxe-grid
      v-bind="gridOptions"
      ref="request_grid"
      @cell-dblclick="handleCellDblclick"
    >
      <template #toolbar_buttons>
        <vxe-button @click="showEditEvent">新增</vxe-button>
        <vxe-button @click="deleteEvent">删除</vxe-button>
      </template>
    </vxe-grid>

    <vxe-modal
      v-model="showEdit"
      :title="selectRow ? '编辑&保存' : '新增&保存'"
      width="800"
      min-width="600"
      min-height="300"
      :loading="submitLoading"
      resize
      destroy-on-close
    >
      <template #default>
        <vxe-form
          :data="formData"
          :items="formItems"
          :rules="formRules"
          title-align="right"
          title-width="100"
          @submit="submitEvent"
        ></vxe-form>
      </template>
    </vxe-modal>
  </d2-container>
</template>

<script>
import XEUtils from 'xe-utils'
import { Message } from 'element-ui'
import RequestApi from '@/module/system/api/request.api'
import CodeMirror from 'codemirror/lib/codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/ambiance.css'
require('codemirror/mode/javascript/javascript')

export default {
  data() {
    return {
      showEdit: false,
      submitLoading: false,
      isUpdateForm: false,
      formData: {
        'Request.tag': '',
        'Request.method': '',
        'Request.structure': '',
        'Request.detail': ''
      },
      formItems: [
        { title: '请求参数校验配置', span: 24, titleAlign: 'left', titleWidth: 200, titlePrefix: { icon: 'fa fa-address-card-o' } },
        { field: 'Request.tag', title: '模型/表', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入模型/表名称' } } },
        { field: 'Request.method', title: '方法名', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入校验规则' } } },
        { field: 'Request.structure', title: '参数', span: 24, class: 'json-editor',ref: 'json_editor', itemRender: { name: '$textarea', ref: 'json_editor', props: { ref: 'json_editor', placeholder: '请输入规则' } }, titleSuffix: { message: '提示信息！！', icon: 'fa fa-question-circle' } },
        { field: 'Request.detail', title: '规则描述', span: 24, itemRender: { name: '$textarea' } },
        { align: 'center', span: 24, titleAlign: 'left', itemRender: { name: '$buttons', children: [{ props: { type: 'submit', content: '提交', status: 'primary' } }, { props: { type: 'reset', content: '重置' } }] } }
      ],
      formRules: {
        'Request.tag': [
          { required: true, message: '请输入模型/表名称' },
          { min: 3, max: 20, message: '长度在 3 到 5 个字符' }
        ],
        'Request.method': [
          { required: true, message: '请输入方法名' }
        ],
        'Request.structure': [
          { required: true, message: '请输入校验规则' }
        ]
      },
      gridOptions: {
        resizable: true,
        border: true,
        showOverflow: true,
        loading: false,
        height: 'auto',
        rowId: 'rowId',
        exportConfig: {},
        formConfig: {
          items: [
            { field: 'tag', title: '目标', span: 8, align: 'center', itemRender: { name: '$input', props: { placeholder: '请输入模型名' } } },
            {
              itemRender: {
                name: '$buttons',
                children: [
                  { props: { type: 'submit', content: '查询', status: 'primary' } },
                  { props: { type: 'reset', content: '重置' } }
                ]
              }
            }
          ]
        },
        toolbarConfig: { slots: { buttons: 'toolbar_buttons' }, refresh: true, import: true, export: true, print: true, zoom: true, custom: true },
        proxyConfig: {
          seq: true, // 启用动态序号代理（分页之后索引自动计算为当前页的起始序号）
          form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
          props: {
            result: '[]',
            total: 'total'
          },
          ajax: {
            // 接收 Promise
            query: ({ page, sorts, filters, form }) => {
              console.log(page)
              console.log(form)
              const params = Object.assign({}, form)
              return RequestApi.page({
                page: page.currentPage - 1,
                limit: page.pageSize,
                params: params
              })
            }
          }
        },
        pagerConfig: { pageSize: 10 },
        columns: [
          { type: 'seq', width: 60 },
          { type: 'checkbox', width: 60 },
          { field: 'Request.tag', title: '对象名' },
          { field: 'Request.method', title: '方法' },
          { field: 'Request.structure', title: '参数', formatter: this.formatJsonObject },
          { field: 'Request.detail', title: '说明' },
          { field: 'Request.version', title: '版本' },
          { field: 'Request.date', formatter: this.formatDate, title: '日期', showOverflow: true }
        ]
      }
    }
  },
  mounted() {
    this.editor = CodeMirror.fromTextArea(this.$refs.json_editor, {
      mode: 'text/json',
      theme: 'ambiance'
    })
  },
  methods: {
    formatDate(params) {
      return XEUtils.isNull(params.cellValue) ? '' : params.cellValue.substr(0, 19)
    },
    formatJsonObject(params) {
      return XEUtils.toJSONString(params.cellValue)
    },
    handleCellClickEvent({ row }) {
      console.log(row)
    },
    handleCellDblclick({ row }) {
      console.log(row)
      const grid = this.$refs.request_grid
      console.log(grid)
      grid.toggleCheckboxRow(row)
      this.showEditEvent()
    },
    showEditEvent() {
      const records = this.$refs.request_grid.getCheckboxRecords()
      var record = {}
      if (!XEUtils.isEmpty(records)) {
        record = records[0]
      }
      if (XEUtils.isEmpty(record)) {
        this.isUpdateForm = false
      } else {
        this.isUpdateForm = true
      }
      this.showEdit = true
      this.formData = XEUtils.assign({}, record)
      this.formData.Request.structure = XEUtils.toJSONString(this.formData.Request.structure)
    },
    submitEvent() {
      const grid = this.$refs.request_grid
      if (this.isUpdateForm) {
        RequestApi.update(this.formData).then(response => {
          this.showEdit = false
          this.$nextTick(() => grid.commitProxy('reload'))
        })
      } else {
        RequestApi.save(this.formData).then(response => {
          this.showEdit = false
          this.$nextTick(() => grid.commitProxy('reload'))
        })
      }
    },
    deleteEvent() {
      const grid = this.$refs.request_grid
      const records = grid.getCheckboxRecords()
      if (XEUtils.isEmpty(records)) {
        Message({
          message: '请选择一条或多条记录',
          type: 'error',
          duration: 5 * 1000
        })
        return
      }
      RequestApi.deleteBatch(records).then(response => this.$nextTick(() => { grid.commitProxy('reload') }))
    }
  }
}
</script>
<style lang="scss" scoped>
.json-editor {
  height: 100%;
  position: relative;

  ::v-deep {
    .CodeMirror {
      height: auto;
      min-height: 300px;
    }

    .CodeMirror-scroll {
      min-height: 300px;
    }

    .cm-s-rubyblue span.cm-string {
      color: #F08047;
    }
  }
}
</style>
